import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:hxdj/common/base_page/my_loading_page.dart';
import 'package:hxdj/common/components/my_clip_rect.dart';
import 'package:hxdj/common/components/my_smart_refresher.dart';
import 'package:hxdj/common/components/my_tap_widget.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_common.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/my_header_global.dart';
import 'package:hxdj/common/routers/navigator.dart';
import 'package:hxdj/common/utils/my_event_bus_util.dart';
import 'package:hxdj/home/order/order_detail/order_detail_page.dart';
import 'package:hxdj/home/order/order_manager.dart';
import 'package:hxdj/home/order/order_model.dart';
import 'package:hxdj/home/order/order_view_model.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class OrderItemPage extends StatefulWidget {
  final String orderStatus;
  const OrderItemPage({super.key, required this.orderStatus});

  @override
  State<OrderItemPage> createState() => _OrderItemPageState();
}

class _OrderItemPageState extends State<OrderItemPage> with AutomaticKeepAliveClientMixin {
  late OrderViewModel viewModel;

  late ScrollController? scrollController;

  late RefreshController? refreshController;

  late StreamSubscription onEventResult;

  @override
  bool get wantKeepAlive {
    return true;
  }

  @override
  void initState() {
    super.initState();
    scrollController = ScrollController();
    refreshController = RefreshController();

    onEventResult = MyEventBusUtil.onEventResult((value) {
      //接收到信息
      if (value.tag == MyEventBusTag.refreshOrderList) {
        viewModel.requestData(orderStatus: widget.orderStatus, isFrist: true);
      }
    });
  }

  @override
  dispose() {
    onEventResult.cancel();
    super.dispose();
  }

  _buildBody() {
    switch (viewModel.state) {
      case ViewState.loading:
        return const MyLoadingWidget();
      case ViewState.empty:
        return Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              MyImage(imageName: "ic_message_nodate", width: 150.w, height: 150.w),
              Container(
                padding: EdgeInsets.only(top: 25.h),
                child: RichText(
                    text: TextSpan(
                        style: TextStyle(color: MyColours.colorA2A2A2, fontSize: 12.sp, height: 1.2),
                        children: [
                      const TextSpan(text: '您还没有订单哦，去'),
                      TextSpan(
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              debugPrint("点击了下单");
                              Navigator.of(context).popUntil((route) => route.isFirst);
                              MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
                              globalViewModel.setIndex(1);
                            },
                          text: '下单',
                          style: const TextStyle(color: MyColours.appMain)),
                      const TextSpan(text: '试试吧～'),
                    ])),
              ),
            ],
          ),
        );
      default:
        List<OrderModel>? dataList = viewModel.dataMap[widget.orderStatus] ?? [];

        bool isHaveData = viewModel.isHaveMap[widget.orderStatus] ?? false;

        if (dataList.isEmpty) {
          return MyImage(imageName: "ic_message_nodate", width: 100.w, height: 100.w);
        }

        //刷新完成
        refreshController!.refreshToIdle();
        refreshController!.loadComplete();

        if (!isHaveData) {
          //无更多数据
          refreshController!.loadNoData();
        }

        return Container(
            color: MyColours.bgColor,
            child: MySmartRefresher(
              dataList: dataList,
              enablePullUp: true,
              enablePullDown: true,
              noMoreData: !isHaveData,
              scrollController: scrollController!,
              itemBuilder: (BuildContext context, int index) {
                return OrderItem(
                  orderModel: dataList[index],
                  margin: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.h, bottom: 10.h),
                  padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 10.h, bottom: 10.h),
                );
              },
              controller: refreshController!,
              onLoading: () {
                viewModel.requestData(orderStatus: widget.orderStatus, isFrist: false);
              },
              onRefresh: () {
                //下拉刷新
                refreshController!.loadComplete;
                viewModel.requestData(orderStatus: widget.orderStatus, isFrist: true);
              },
            ));
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BasePage<OrderViewModel>(
        onModelReady: (model) async {
          // 页面初始化完成后的回调
          viewModel = model;
          viewModel.requestData(orderStatus: widget.orderStatus, isFrist: true);
        },
        viewModel: OrderViewModel(),
        builder: (BuildContext context, OrderViewModel model, Widget? child) {
          return _buildBody();
        });
  }
}

//订单it
class OrderItem extends StatelessWidget {
  final OrderModel orderModel;
  final EdgeInsetsGeometry? margin;
  final EdgeInsetsGeometry? padding;
  const OrderItem({super.key, this.margin, this.padding = EdgeInsets.zero, required this.orderModel});

  /// 1. button_groups：
  /// 1,  //取消订单 2,  //立即支付 3,  //联系商家 4,  //确认完成 5,  //立即接单 6,  //联系客户 7,  //删除订单 8,  //再次购买 9,  //确认码 10, //我已出发 11, //我已到达 12, //开始服务 13, //完成服务 14, //重要提示 15  //更换服务者

  @override
  Widget build(BuildContext context) {
    String buttonGroups = orderModel.buttonGroups ?? "";
    List<String> buttonGroupsList = buttonGroups.split(",");

    return MyTapWidget(
      onTap: () {
        NavigatorUtils.pushParams(context, '${OrderDetailPage.routeName}?orderId=${orderModel.orderId}');
      },
      child: Container(
          margin: margin ?? EdgeInsets.only(left: 15.w, right: 15.w, top: 10.h, bottom: 10.h),
          padding: padding,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10.w),
          ),
          child: Column(children: [
            Container(
              padding: EdgeInsets.only(bottom: 10.h),
              decoration: const BoxDecoration(
                border: Border(
                  bottom: BorderSide(color: MyColours.line, width: 1),
                ),
              ),
              child: Row(
                children: [
                  MyClipRect(
                    imageUrl: orderModel.memberImg ?? "",
                    width: 22.w,
                    radius: 11.w,
                    height: 22.w,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 10.w),
                    child: Text(orderModel.nickname ?? "", style: MyTextStyles.textBold14),
                  ),
                  const Spacer(),
                  MyText(
                    orderModel.orderTips ?? "",
                    color: MyColours.colorFF4414,
                    fontSize: 12.sp,
                  ),
                ],
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: 10.h, bottom: 10.h),
              child: Row(
                children: [
                  MyClipRect(
                    imageUrl: orderModel.imImg ?? "",
                    width: 60.w,
                    radius: 12.w,
                    height: 60.w,
                  ),
                  Container(
                    padding: const EdgeInsets.only(left: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Text(orderModel.goodsTitle ?? "", style: TextStyle(color: MyColours.text, fontSize: 14.sp)),
                            Text("  x${orderModel.payNum ?? ""}",
                                style: TextStyle(color: MyColours.textGray, fontSize: 14.sp)),
                          ],
                        ),
                        MyGaps.vGap16,
                        Text("预约时间：${orderModel.orderServiceTime ?? ""}",
                            style: TextStyle(color: MyColours.textGray, fontSize: 11.sp)),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Container(
                      alignment: Alignment.centerRight,
                      child: Text("${orderModel.orderPrice}",
                          style: TextStyle(color: MyColours.text, fontSize: 12.sp, fontWeight: FontWeight.w600)),
                    ),
                  ),
                ],
              ),
            ),
            CommonPlugin.isEmpty(buttonGroupsList.isNotEmpty)
                ? Container()
                : Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: buttonGroupsList.map((e) {
                      return CommonPlugin.isEmpty(titleMap[e] ?? "")
                          ? Container()
                          : Container(
                              margin: EdgeInsets.only(left: 15.w),
                              child: GestureDetector(
                                  onTap: () {
                                    //统一了点击事件
                                    OrderManager.clickFuntion(
                                        e, context, orderModel.orderId.toString(), orderModel.memberId.toString(),
                                        price: orderModel.orderPrice ?? "", onSure: (bool isSuccess) {});
                                  },
                                  child: MyBorder(
                                      width: 1,
                                      backgroundColor: MyColours.materialBg,
                                      color: MyColours.colorE1E1E1,
                                      radius: 12.w,
                                      child: Container(
                                        padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.h),
                                        child: Text(
                                          titleMap[e] ?? "",
                                          style: TextStyle(
                                              color: MyColours.color676767,
                                              fontSize: 10.sp,
                                              fontWeight: FontWeight.w600),
                                        ),
                                      ))),
                            );
                    }).toList())
          ])),
    );
  }
}
